import { Toast } from "vant";
import { login } from "@/request/login-request";
import request from "@/api/request";
import { UPDATE_LINE_STATUS_API } from "@/api/api_constant";
import store from "@/store";

const state = store.state;
const socketState = state.socket;

export const useLogin = async (store,router,show, qq_account) => {
  try {
    show.value = true;
    const qqAccount = qq_account.value;
    if (!qqAccount || qqAccount.length <= 0 || qqAccount === "") {
      Toast("账号不能为空");
    } else {
      const result = await login(qqAccount);
      if (result.code === 201 && result.message === "success") {
        Toast("登录成功");
        const { user, token } = result.data;
        user.avatar = "http://q4.qlogo.cn/headimg_dl?dst_uin="+user.qq_account+"&spec=100"

        setTimeout(async () => {
          store.dispatch("user/setToken", token);
          user.line_status = "online";
          store.dispatch("user/setUserInfo", user);
          localStorage.setItem("token", token);
          localStorage.setItem("userInfo", JSON.stringify(user));
          await request.put(UPDATE_LINE_STATUS_API, {
            _id: user._id,
            qq_account: user.qq_account,
            line_status: "online",
          });
          router.replace({
            path: "/message",
          });
        }, 500);
      } else {
        Toast(result.message);
      }
    }
    show.value = false;
  } catch (error) {
    Toast("发生错误，错误信息：" + error.message);
  }
};
